<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use DateTimeInterface;
use Illuminate\Support\Facades\Cache;

class RoleAuth extends Model
{
    use HasFactory;
    protected $table = 'lb_role_auth';
    protected $primarykey = 'id';
    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'update_time';
    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }


    /**
     * @return start 配置后台主页参数
     */
    public static function setAuthinfo(){
        Cache::flush();
        if(!Cache::has('authinfo')){
            return self::getAuthinfo();
        }
        return Cache::get('authinfo');
    }
    protected static function getAuthinfo(){
//        $authinfo = self::where('status','=','1')->where('is_show','=','1')
//            ->orderBy('order', 'desc')
//            ->select('auth_name as title','auth_url as href','icon','id','pid')
//            ->get()->toArray();
//        \DB::connection()->enableQueryLog();
        $authinfo = self::leftJoin('lb_auth','lb_role_auth.auth_id','=','lb_auth.id')
                        ->where('lb_role_auth.role_id','=',session('user.role_id'))
                        ->where('lb_role_auth.status','=','1')
                        ->where('lb_auth.is_show','=','1')
                        ->orderBy('lb_auth.order','desc')
                        ->select('lb_auth.auth_name as title','lb_auth.auth_url as href','lb_auth.icon','lb_auth.id','lb_auth.pid')
            ->get()->toArray();

//        $queries = \DB::getQueryLog();
//        dump($queries);
//        return $authinfo;
        //权限树状图
        $authinfo_tree = getChildTree($authinfo);
        $arr = self::system();
        $arr['menuInfo'] = $authinfo_tree;
        $arr = json_encode($arr);
        Cache::forever('authinfo',$arr);
        return $arr;
    }
    protected static function system(){
        $arr = [];
        $arr['homeInfo']['title'] = '首页';
        $arr['homeInfo']['href'] = '/manage/welcome';
        $arr['logoInfo']['title'] = 'layui mini';
        $arr['logoInfo']['image'] = 'web/images/logo.png';
        $arr['logoInfo']['href'] = '';
        return $arr;
    }
    /**
     * end
     */

    public static function getUserAuthList($role_id){
        return self::leftJoin('lb_auth','lb_auth.id','=','lb_role_auth.auth_id')->where('lb_role_auth.role_id','=',$role_id)->where('lb_role_auth.status','=','1')->pluck('lb_auth.auth_url')->toArray();
    }
}
